package 力扣.数组;

import java.util.Arrays;

public class 除自身以外数组的乘积238 {
    public static void main(String[] args) {
//        int[] ints = new int[]{1,2,3,4};
        int[] ints = new int[]{0,0};
        int[] ints1 = productExceptSelf2(ints);
        System.out.println(Arrays.toString(ints1));
    }

    /**
     * 错误帮：遇到含有元素 0 时会报错（0不能作为除数）
     * 先计算所有元素的乘积 to，然后用to除以当前元素即可以得到结果
     *
     * @param nums
     * @return
     */
    public static int[] productExceptSelf(int[] nums) {
        int length = nums.length;
        int te = 1;
        for (int i = 0; i < length; i++) {
            te *= nums[i];
        }
        for (int i = 0; i < length; i++) {
            nums[i] = te/nums[i];
        }
        return nums;
    }

    /**
     * 进阶版：开辟两个数组L[i]、R[i] 分别代表 i 左侧所有元素的乘积 右侧所有元素的乘积
     * 而 L[i] = L[i-1] * num[i-1]  初始值 L[0] = 1;
     *   R[i] = R[i+1] * num[i+1]  初始值 R[length-1] = 1;
     * @param nums
     * @return
     */
    public static int[] productExceptSelf2(int[] nums) {
        int length = nums.length;
        int[] L = new int[length];
        int[] R = new int[length];
        L[0] = 1;
        R[length-1] = 1;
        for (int i = 1; i < length; i++) {
            L[i] = L[i-1] * nums[i-1];//从左到右计算
            R[length-1-i] = R[length -i] * nums[length -i]; //从右到左计算
        }

        for (int i = 0; i < length ; i++) {
            nums[i] = L[i] * R[i];
        }
        return nums;

    }
}
